package com.guigu.servicegoods.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.common_util.pojo.utils.Result;
import com.guigu.servicegoods.domain.TbSpec;
import com.guigu.servicegoods.domain.TbTemplate;
import com.guigu.servicegoods.service.TbSpecService;
import com.guigu.servicegoods.service.TbTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@RestController
@RequestMapping("/servicegoods/tbspec")
public class TbSpecController {

    @Autowired
    private TbSpecService specService;

    @Autowired
    private TbTemplateService templateService;

    @GetMapping("findByTemplateId")
    public Result findByTemplateId(Integer templateId){
        QueryWrapper<TbSpec> wrapper = new QueryWrapper<>();
        wrapper.eq("template_id",templateId);
        List<TbSpec> spec = specService.list(wrapper);
        if (spec == null){
            return Result.error();
        }
        return Result.ok().data("spec",spec);
    }

    @PostMapping("fingPage")
    public Result findPage(@RequestBody(required = false) Map<String,Object> searchMap, Integer page, Integer size){
        return specService.findPage(searchMap,page,size);
    }

    @PostMapping("insert")
    public Result insert(@RequestBody TbSpec spec){
        if(specService.save(spec)){
            TbTemplate template = templateService.getById(spec.getTemplateId());
            Integer specNum = template.getSpecNum()+1;
            template.setSpecNum(specNum);
            templateService.updateById(template);
            return Result.ok();
        }
        return Result.error();
    }

    @PostMapping("update")
    public Result update(@RequestBody TbSpec spec){
        if (specService.updateById(spec)){
            return Result.ok();
        }
        return Result.error();
    }

    @GetMapping("delete")
    public Result delete(Integer id){
        TbSpec spec = specService.getById(id);
        if (specService.removeById(id)){
            TbTemplate template = templateService.getById(spec.getTemplateId());
            Integer specNum = template.getSpecNum()-1;
            template.setSpecNum(specNum);
            templateService.updateById(template);
            return Result.ok();
        }
        return Result.error();
    }

    @GetMapping("findById")
    public Result findById(Integer id){
        TbSpec spec = specService.getById(id);
        if (spec == null){
            return Result.error();
        }
        return Result.ok().data("spec",spec);
    }
}

